package com.ccys.cms.service.userManagement.impl;


import cn.hutool.core.util.ObjectUtil;
import com.ccys.cms.service.discount.PromoCodeAutomatedService;
import com.ccys.cms.service.userManagement.TblMemberWebService;
import com.ccys.common.util.Kit;
import com.ccys.common.util.StringUtil;
import com.ccys.common.vo.ResponseResult;
import com.ccys.db.dto.discount.MatchingPremiumCouponsDto;
import com.ccys.db.dto.userManagement.TblMemberDTO;
import com.ccys.db.entity.TblBookingBenefitConsult;
import com.ccys.db.entity.TblBookingBenefitConsultAdjustment;
import com.ccys.db.entity.TblCountry;
import com.ccys.db.entity.TblMember;
import com.ccys.db.mapper.TblBookingBenefitConsultAdjustmentMapper;
import com.ccys.db.mapper.TblBookingBenefitConsultMapper;
import com.ccys.db.mapper.TblCountryMapper;
import com.ccys.db.mapper.TblMemberMapper;
import com.ccys.db.page.PageUtils;
import com.ccys.db.rely.service.impl.BaseServiceImpl;
import com.ccys.db.service.BaseTblAuditTrailWebService;
import com.ccys.db.vo.userManagement.TblMemberDetailWebVO;
import com.ccys.db.vo.userManagement.TblMemberWebVO;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;


/**
 * tbl_member管理
 */
@Service
@Slf4j
public class TblMemberWebServiceImpl extends BaseServiceImpl<TblMember> implements TblMemberWebService {

    @Autowired(required = false)
    private TblMemberMapper tblMemberMapper;
    @Autowired(required = false)
    private PromoCodeAutomatedService promoCodeAutomatedService;
    @Autowired(required = false)
    private BaseTblAuditTrailWebService baseTblAuditTrailWebService;

    @Resource
    private TblBookingBenefitConsultMapper tblBookingBenefitConsultMapper;

    @Resource
    private TblBookingBenefitConsultAdjustmentMapper tblBookingBenefitConsultAdjustmentMapper;

    @Resource
    private TblCountryMapper tblCountryMapper;


    @Override
    public ResponseResult listObjectsCms(HttpServletRequest request, HttpServletResponse response, TblMemberDTO dto) {
        if (StringUtil.isNotEmpty(dto.getEndAge())) {
            dto.setStartAge(Kit.getBirthday(Integer.parseInt(dto.getEndAge())));
        }
        if (StringUtil.isNotEmpty(dto.getStartAge())) {
            dto.setEndAge(Kit.getBirthday(Integer.parseInt(dto.getStartAge())));
        }
        PageUtils.startPage(request);
        List<TblMemberWebVO> list = this.tblMemberMapper.listObjectsCms(dto);
        PageInfo pageInfo = new PageInfo<>(list);
        return ResponseResult.success(pageInfo);
    }


    @Override
    public ResponseResult change(TblMember entity) {
        List<String> whereList = new ArrayList<>();
        //是否处理优惠券邮箱业务
        boolean flag = false;
        if (StringUtils.isBlank(entity.getId())) {
            if (entity.getStatus() == null) {
                entity.setStatus(1);
            }
            if(StringUtil.isEmpty(entity.getMemberNo())) {
                return ResponseResult.error("MemberNo  is  must ");
            }
            //公共接口提前生成
            //String code = getCode();
            //entity.setMemberNo(code);
            entity.setPassword(Kit.getPassword(entity.getPassword()));
            if (entity.getGender() == null) {
                entity.setGender(-1);
            }
            if (entity.getActived() == null) {
                entity.setActived(0);
            }
            if (entity.getStatus() == null) {
                entity.setStatus(1);
            }

            whereList.clear();
            whereList.add("del_flag=0");
            whereList.add("(nric_fin='" + entity.getNricFin() + "' or email='" + entity.getEmail() + "')");
            TblMember oneByLimit = this.findOneByLimit(TblMember.class, whereList);
            if (oneByLimit != null) {
                return ResponseResult.error("nricFin or email is Already exists");
            }
            // 新增
            this.saveEntity(entity);
            flag = true;

        } else {
            TblMember entityById = this.findEntityById(entity.getId());
            if (entityById == null) {
                return ResponseResult.error("object is not exists");
            }
            if (!entityById.getNricFin().equals(entity.getNricFin())) {
                whereList.clear();
                whereList.add("del_flag=0");
                whereList.add("(nric_fin='" + entity.getNricFin() + "')");
                TblMember oneByLimit = this.findOneByLimit(TblMember.class, whereList);
                if (oneByLimit != null) {
                    return ResponseResult.error("nricFin is Already exists");
                }
            }
            if (entity.getEmail() != null && !entityById.getEmail().equals(entity.getEmail())) {
                whereList.clear();
                whereList.add("del_flag=0");
                whereList.add("(email='" + entity.getEmail() + "')");
                TblMember oneByLimit = this.findOneByLimit(TblMember.class, whereList);
                if (oneByLimit != null) {
                    return ResponseResult.error("email is Already exists");
                }
                flag = true;
            }
            // 编辑
            this.updateEntityById(entity);
            if (entity.getStatus() != null) {
                this.baseTblAuditTrailWebService.saveStatusLog(entity, entity.getStatus());
            }
        }
        if (flag) {
            MatchingPremiumCouponsDto matchingPremiumCouponsDto = new MatchingPremiumCouponsDto();
            matchingPremiumCouponsDto.setId(entity.getId());
            matchingPremiumCouponsDto.setEmail(entity.getEmail());
            matchingPremiumCouponsDto.setNricFin(entity.getNricFin());
            //设置fullName
            matchingPremiumCouponsDto.setFullName(
                    Optional.ofNullable(entity.getFirstName()).orElse("") +
                            Optional.ofNullable(entity.getLastName()).orElse(""));
            //设置国家ID
            matchingPremiumCouponsDto.setCountryId(entity.getPhoneCountryId());
            //查询当前用户所在国家的货币符号
            TblCountry country = tblCountryMapper.selectByPrimaryKey(entity.getPhoneCountryId());
            //判断这个国家必须存在并且货币符号不为空
            if (ObjectUtil.isNotEmpty(country) && ObjectUtil.isNotEmpty(country.getCurrency())) {
                matchingPremiumCouponsDto.setCurrency(country.getCurrency());
            } else {
                //否则设置为美金符号
                matchingPremiumCouponsDto.setCurrency("$");
            }
            //异步处理优惠券与邮箱业务
            CompletableFuture.runAsync(() -> {
                try {
                    promoCodeAutomatedService.queryAvailablePremiumCouponsByEmail(matchingPremiumCouponsDto);
                } catch (Exception e) {
                    log.error("异步处理优惠券与邮箱业务异常！！！", e);
                }

            });
        }
        return ResponseResult.success();
    }

    @Override
    @NotNull
    public String getCode() {
        String code = Kit.getCodeStr();
        List<String> whereList = new ArrayList<>();
        whereList.clear();
        whereList.add("del_flag=0");
        whereList.add("member_no= '" + code + "'");
        TblMember oneByLimit = this.findOneByLimit(TblMember.class, whereList);
        if (oneByLimit != null) {
            code = getCode();
        }
        return code;
    }

    @Override
    public ResponseResult delete(TblMember dto) {
        TblMember entity = new TblMember();
        entity.setId(dto.getId());
        entity.setDelFlag(1);
        this.updateEntityById(entity);
        return ResponseResult.success();
    }

    @Override
    public ResponseResult getMemberDetail(HttpServletRequest request, HttpServletResponse response, TblMemberDTO dto) {
        TblMemberDetailWebVO tblMemberDetailWebVO = this.tblMemberMapper.getMemberDetail(dto);
        return ResponseResult.success(tblMemberDetailWebVO);
    }

    @Override
    public ResponseResult listSelect(HttpServletRequest request, HttpServletResponse response, TblMemberDTO dto) {
        //PageUtils.startPage(request);
        List<TblMemberWebVO> list = this.tblMemberMapper.listSelect(dto);
        //PageInfo pageInfo = new PageInfo<>(list);
        return ResponseResult.success(list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult updatePatientInfoConsultationsAdjust(TblBookingBenefitConsult dto) {
        Kit.allParamValid(dto, "id", "adjustmentReason", "visitCount", "claimAmount");
        //查询老数据
        TblBookingBenefitConsult dbBenefitConsult = tblBookingBenefitConsultMapper.findById(dto.getId());
        //准备修改记录对象
        TblBookingBenefitConsultAdjustment adjustment = new TblBookingBenefitConsultAdjustment();
        adjustment.setConsultId(dbBenefitConsult.getId());
        adjustment.setClaimAmountBeforeAdjustment(dbBenefitConsult.getClaimAmount());
        adjustment.setClaimAmountAfterAdjustment(dto.getClaimAmount());
        adjustment.setVisitCountBeforeAdjustment(dbBenefitConsult.getVisitCount());
        adjustment.setVisitCountAfterAdjustment(dto.getVisitCount());
        adjustment.setAdjustmentReason(dto.getAdjustmentReason());
        adjustment.setAdditionalClaimAmountBeforeAdjustment(dbBenefitConsult.getAdditionalClaimAmount());
        adjustment.setAdditionalClaimAmountAfterAdjustment(dto.getAdditionalClaimAmount());
        //修改tblBookingBenefitConsult
        tblBookingBenefitConsultMapper.updateByPrimaryKeySelective(dto);
        //新增TblBookingBenefitConsultAdjustment
        tblBookingBenefitConsultAdjustmentMapper.insertSelective(adjustment);
        return ResponseResult.success("Operation successful");
    }


}